using System;
using System.Collections.Specialized;
using Kwan.Data;
using System.Text;
using System.Collections.Generic;
using System.Web;

namespace Kwan.Web
{
    public class BaseFacade<T,V>
        where T : Kwan.Data.Mappings.DataObject, new()
        where V : Kwan.Data.Mappings.DataObject, new()
    {
        private IQueryBuilder _queryBuilder;
        public IQueryBuilder QueryBuilder
        {
            get { return _queryBuilder; }
            set { _queryBuilder = value; }
        }

        public BaseFacade()
        {
            //this._logger = LogManager.GetLogger(typeof(BaseFacade<TEntity, VEntity, TKey>));
            //this._service = new BaseService<TEntity, VEntity, TKey>();
        }

        public string Execute(NameValueCollection args)
        {
            string message = "";
            string str2 = args["s_method"];
            if ("list".Equals(str2))
            {
                message = LoadJSON(args);
            }
            else if ("save".Equals(str2))
            {
                message = Save(args);
            }
            else if ("delete".Equals(str2))
            {
                message = DeleteByID(args);
            }
            else
            {
                message = JSON.ExtResult("false", "0");
            }
            return message;
        }

        public static string Extend(bool flag)
        {
            return "{\"success\": " + flag + ",\"data\":\"OK\"}";
        }

        protected string LoadJSON(NameValueCollection args)
        {
            string query = args["query1"];
            string strStart = args["start"];
            string strLimit = args["limit"];
            List<Sort> sort = new List<Sort>();
            if (!string.IsNullOrEmpty(args["sort"]))
                sort = JSON.Deserialize<List<Sort>>(args["sort"]);
            StringBuilder sbSort = new StringBuilder();
            for (int i = 0; i < sort.Count;i++ )
            {
                sbSort.Append(sort[i].property);
                sbSort.Append(" ");
                sbSort.Append(sort[i].direction);
                if (i < sort.Count - 1)
                    sbSort.Append(",");
            }
            int start = 0;
            int pageSize = 10;
            if (!string.IsNullOrEmpty(strStart))
            {
                start = int.Parse(strStart);
            }
            if (!string.IsNullOrEmpty(strLimit))
            {
                pageSize = int.Parse(strLimit);
            }
            using (IConnectinContext cc = DBContext.Context1)
            {
                NameValueCollection ps = this.MakeQueryArgs(query);
                Region region = new Region() { Start = start, Size = pageSize };
                Expression exp = this.QueryBuilder.MakeSearchWhere(ps);
                IList<V> list = exp.List<V>(region, sbSort.ToString());
                int total = exp.Count<V>();
                string data = JSON.Serialize(list);
                return JSON.ExtResult("true", JSON.ExtGridResult(total, data));
            }
            
        }

        protected NameValueCollection MakeQueryArgs(string query)
        {
            NameValueCollection values = new NameValueCollection();
            if (query != null)
            {
                string[] strArray = query.Split("&".ToCharArray());
                if (strArray[0].IndexOf('=') < 0)
                {
                    return values;
                }
                foreach (string str in strArray)
                {
                    string[] strArray2 = str.Split("=".ToCharArray());
                    if (strArray2.Length != 2)
                    {
                        throw new Exception("请查对查询字符串:" + query);
                    }
                    values.Add(strArray2[0], strArray2[1]);
                }
            }
            return values;
        }

        protected string Save(NameValueCollection args)
        {
            int result = 0;
            bool flag = true;
            bool isAdd = string.IsNullOrEmpty(args["EntityID"]);
            string data = HttpUtility.UrlDecode(args["data"]);
            try
            {
                T obj = JSON.Deserialize<T>(data);
                obj.EntityState._Loaded = !isAdd;
                result = DBContext.Save(obj);
            }
            catch
            {
                flag = false;
            }
            return JSON.ExtResult(flag.ToString().ToLower(), result.ToString());
        }

        public string DeleteByID(NameValueCollection args)
        {
            bool flag = false;
            string[] list = args["id"].Split(',');
            StringBuilder sb = new StringBuilder();
            string pj = typeof(T).FullName.Replace(".Data.T", "_");
            for (int i = 0; i < list.Length; ++i)
            {
                if (i == 0)
                {
                    sb.Append("DELETE FROM ");
                    sb.Append(pj);
                    sb.Append(" WHERE");
                }
                else
                    sb.Append(" OR");
                sb.Append(" EntityID=");
                sb.Append(list[i]);
            }
            using (IConnectinContext cc = DBContext.Context1)
            {
                Command cmd = new Command(sb.ToString());
                flag = cc.ExecuteNonQuery(cmd) > 0;
            }
            return JSON.ExtResult(flag.ToString().ToLower(), "0");
        }
    }
}

